package com.tiktok.config;

import lombok.RequiredArgsConstructor;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Web配置类
 */
@Configuration
@RequiredArgsConstructor
public class WebConfig implements WebMvcConfigurer {

    private final JwtAuthenticationInterceptor jwtAuthenticationInterceptor;
    private final LoggingInterceptor loggingInterceptor;
    private final RequestResponseCachingFilter requestResponseCachingFilter;

    /**
     * 注册请求响应缓存过滤器
     */
    @Bean
    public FilterRegistrationBean<RequestResponseCachingFilter> requestResponseCachingFilterRegistration() {
        FilterRegistrationBean<RequestResponseCachingFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(requestResponseCachingFilter);
        registration.addUrlPatterns("/*");
        registration.setOrder(1);
        return registration;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 添加日志拦截器
        registry.addInterceptor(loggingInterceptor)
                .addPathPatterns("/**");
        
        // 添加JWT认证拦截器
        registry.addInterceptor(jwtAuthenticationInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns(
                        "/user/login",
                        "/user/register",
                        "/video/recommend",
                        "/files/**",          // 排除文件访问路径
                        "/upload/video",      // 排除视频上传路径  
                        "/upload/image",      // 排除图片上传路径
                        "/error",
                        "/actuator/**",
                        "/swagger-ui/**",
                        "/v3/api-docs/**"
                );
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600);
    }
} 